package com.oanda.blackberry.net;

import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;

import com.oanda.blackberry.util.Model;

public class ConnectionManager {
    static final String GAME_API_URL = "https://fxgame-webapi.oanda.com/";
    static final String TRADE_API_URL = "https://fxtrade-webapi.oanda.com/";
    static int index;
    static String[] urls = { "https://fxgame-webapi.oanda.com/",
            "https://fxtrade-webapi.oanda.com/" };

    static String[] urlsFriendlyNames = { "fxgame", "fxtrade" };

    private static String[] connectionSuffix = { ";deviceside=false",
            ";deviceside=true;interface=wifi", ";deviceside=true", "",
            ";deviceside=true;ConnectionUID=" + getWap2Uid() };

    public static String getUrl() {
        return urls[Model.getModel().getUrlIndex()];
    }

    public static String getUrlFriendlyName() {
        return urlsFriendlyNames[Model.getModel().getUrlIndex()];
    }

    public static String getConnectionSuffix() {
        return (Model.getModel().isTrustAll() ? ";trustAll" : "")
                + (Model.getModel().isEnableHttpsRedirect() ? ";RdHTTPS" : "")
                + (Model.getModel().isEndToEndRequired() ? ";EndToEndDesired" : "");
    }

    private static String getWap2Uid() {
        ServiceBook sb = ServiceBook.getSB();
        ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
        String uid = null;
        for (int i = 0; i < records.length; i++) {
            if ((!records[i].isValid()) || (records[i].isDisabled()))
                continue;
            if ((records[i].getUid() == null) || (records[i].getUid().length() == 0)
                    || (records[i].getUid().toLowerCase().indexOf("wifi") != -1)
                    || (records[i].getUid().toLowerCase().indexOf("mms") != -1))
                continue;
            uid = records[i].getUid();
            break;
        }

        if (uid != null) {
            return uid;
        }
        return null;
    }
}
